#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_SIZE 4

typedef struct{
	int maxsize;
	int row1;
	int row2;
	int* A;
	int* B;
	int* C;
}MY_ARGS;

void* myfunc(void* args){
	int i,j;
	MY_ARGS* my_args = (MY_ARGS*) args;
	int maxsize = my_args->maxsize;
	int row1 = my_args->row1;
	int row2 = my_args->row2;
	int * A  = my_args->A;
	int * B  = my_args->B;
	int * C  = my_args->C;
	for(i=row1;i<row2;i++){
		int sum=0;
		for(j=0;j<maxsize;j++){
			sum += A[i*maxsize+j]*B[j];
		}
		C[i]= sum;
	}
	return  NULL;
}
int main(){
	int thread_num = 2;
//数据准备
	int* A=malloc(sizeof(int)* MAX_SIZE*MAX_SIZE);
	int* B=malloc(sizeof(int)* MAX_SIZE);
	int* C=malloc(sizeof(int)* MAX_SIZE);
	int i,j;
	int size = MAX_SIZE/thread_num;
	for(i=0;i<MAX_SIZE*MAX_SIZE;i++){
		A[i]=rand()%5;
	}
	for(i=0;i<MAX_SIZE;i++){
		B[i]=rand()%5;
	}
//cpu亲和性设置

	pthread_attr_t attr1;
	pthread_attr_t attr2;

	pthread_attr_init(&attr1);
	pthread_attr_init(&attr2);

	cpu_set_t cpu_info;
	__CPU_ZERO(&cpu_info);
	__CPU_ZERO(0,&cpu_info);
	pthread_attr_setaffinity_np(&attr1, sizeof(cpu_set_t), &cpu_info);
	__CPU_ZERO(&cpu_info);
    __CPU_SET(1, &cpu_info);
    pthread_attr_setaffinity_np(&attr2, sizeof(cpu_set_t), &cpu_info);

/////debug 1
//	for(i=0;i<MAX_SIZE;i++){
//		int sum=0;
//		for(j=0;j<MAX_SIZE;j++){
//			sum += A[i*MAX_SIZE+j]*B[j];
//		}
//		C[i]= sum;
//	}

////debug2
//	MY_ARGS args;
//	args.maxsize = MAX_SIZE;
//	args.row1 = 0;
//	args.row2 = MAX_SIZE;
//	args.A = A;
//	args.B = B;
//	args.C = C;
//	myfunc(&args);
/// multhread	
	pthread_t th1,th2;
	MY_ARGS args1,args2;
	args1.maxsize = MAX_SIZE;
	args1.row1 = 0;
	args1.row2 = size;
	args1.A = A;
	args1.B = B;
	args1.C = C;
		
	args2.maxsize = MAX_SIZE;
	args2.row1 = size;
	args2.row2 = 2*size;
	args2.A = A;
	args2.B = B;
	args2.C = C;
	pthread_create(&th1,attr1,myfunc,&args1);	
	pthread_create(&th2,attr2,myfunc,&args2);	
	pthread_join(th2,NULL);
	pthread_join(th1,NULL);


//	pthread_t th[thread_num];
//	MY_ARGS args[thread_num];
//	for(i=0;i<thread_num;i++){
//		args[i].maxsize = MAX_SIZE;
//		args[i].row1 = i*size;
//		args[i].row2 = (i+1)*size;
//		args[i].A = A;
//		args[i].B = B;
//		args[i].C = C;
//		pthread_create(&th[i],NULL,myfunc,&args[i]);
//	}	
//	for(i=0;i<thread_num;i++){
//		pthread_join(th[i],NULL);
//	}
/////////////////	show result
	for(i=0;i<MAX_SIZE;i++){
		for(j=0;j<MAX_SIZE;j++)
			printf("%d ",A[i*MAX_SIZE+j]);
		printf("\n");
	}
	for(i=0;i<MAX_SIZE;i++){
		printf("%d\n",B[i]);
	}
	for(i=0;i<MAX_SIZE;i++){
		printf("%d\n",C[i]);
	}
	
	return 0;

}

